package com.foxconn.ipebg.common.system.controller;

import ipebg.mzk.common.util.Page;
import ipebg.mzk.common.util.PropertyPhase;
import ipebg.mzk.facade.entity.MsFile;
import ipebg.mzk.facade.system.service.MsFileService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.foxconn.ipebg.common.base.security.SecurityUserHolder;
import com.foxconn.ipebg.common.base.util.FastDFSClientWrapper;
import com.github.tobato.fastdfs.domain.StorePath;

@RestController
@Controller
@RequestMapping("/fastdfs.do")
public class FileUploadController {
	private static final Log log = LogFactory.getLog(FileUploadController.class);

	@Autowired
	FastDFSClientWrapper fdfsClient;

	@Resource(name = "msFileServiceImpl")
	MsFileService msFileServiceImpl;

	@RequestMapping(params = "action=mainPage")
	public String mainPage(Model model, HttpServletRequest request) {
		String pdObjName = request.getParameter("pdObjName");
		String userCode = SecurityContextHolder.getContext().getAuthentication().getName();
		String filePrefixUrl = PropertyPhase.readData("FASTDFS_HTTP_PREFIX");
		model.addAttribute("filePrefixUrl", filePrefixUrl);
		return "pages/common/base/multi_file_upload";
	}

	// 上傳導入文件
	@RequestMapping(params = "action=uploadFile")
	@ResponseBody
	public String uploadImportFile(HttpServletRequest request) {
		String fileFullUrl, fileType;
		boolean failFlag = false;
		// tmpPath = PropertyPhase.readData("TEMP_FILE_LOCALTION");
		// groupName = PropertyPhase.readData("FASTDFS_STORAGE_GROUP");
		List<MsFile> files = new ArrayList<MsFile>();
		Map<String, Object> result = new HashMap<String, Object>();
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartRequest multipartRequest = (MultipartRequest) request;
			Iterator<String> it = multipartRequest.getFileNames();

			while (it.hasNext()) {
				MultipartFile file = multipartRequest.getFile(it.next());
				if (file != null) {
					fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().toString().length());
					try {
						StorePath storePath = fdfsClient.uploadFile(file);
						MsFile myFile = new MsFile();
						fileFullUrl = fdfsClient.getResAccessUrl(storePath);
						myFile.setFileId(UUID.randomUUID().toString());
						myFile.setFileRealName(file.getOriginalFilename());
						myFile.setFileRemoteName(storePath.getPath());
						myFile.setFileStorageGroup(storePath.getGroup());
						myFile.setFileType(fileType);
						myFile.setFullUrl(fileFullUrl);
						myFile.setEnabled("TRUE");
						myFile.setUploadDatetime(new Date());
						myFile.setUploader(SecurityUserHolder.getCurrentUser().getLoginName());
						files.add(myFile);
						// msFileServiceImpl.save(myFile);
					} catch (Exception e) {
						e.printStackTrace();
						log.error(e.getMessage(), e);
						result.put("false", true);
						return JSON.toJSONString(result);
					}
				}
			}
		}

		try {
			msFileServiceImpl.batchSave(files);
			return JSON.toJSONString(files);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("File upload to fdfs success,but save file info to DB failed! Files info is:" + JSON.toJSONString(files));
			result.put("false", true);
			return JSON.toJSONString(result);
		}
	}

	// query list of file
	@RequestMapping(params = "action=fileListQuery")
	public void fileListQuery(HttpServletRequest request, HttpServletResponse response) {

		int from = Integer.parseInt(request.getParameter("page"));
		int length = Integer.parseInt(request.getParameter("rows"));
		String realFileName = request.getParameter("realFileName");

		try {
			Page filePage = msFileServiceImpl.getFiles(realFileName, from, length);
			Map objMap = new HashMap();
			objMap.put("rows", filePage.getResult());
			objMap.put("total", filePage.getTotalCount());
			//System.out.print(JSON.toJSONString(objMap));
			response.getWriter().write(JSON.toJSONString(objMap));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}
	
	

	@RequestMapping(params = "action=delFiles")
	public void delFiles(HttpServletRequest request, HttpServletResponse response) {
		String allFilesInfo = request.getParameter("allFilesInfo");
		System.out.println(allFilesInfo);
		String fileId = "", fileUrl = "", fileGroup = "";
		MsFile file = null;
		StorePath storePath = null;
		List<MsFile> fileList = new ArrayList<MsFile>();
		List<StorePath> storePathList = new ArrayList<StorePath>();
		String strResult="";
		try {

			if (allFilesInfo == null && allFilesInfo.length() < 2) {
				strResult="ERROR";
				return;
			}
			String[] filesInfo = allFilesInfo.split(";");
			String[] temp;
			for (int i = 0; i < filesInfo.length; i++) {
				if(filesInfo[i].indexOf(":") > 0) {
					temp = filesInfo[i].split(":");
					fileId = temp[0];
					fileGroup = temp[1];
					fileUrl = temp[2];

					file = msFileServiceImpl.findFile(fileId);
					if(file!=null){
						fileList.add(file);
						storePath = new StorePath(fileGroup, fileUrl);
						storePathList.add(storePath);
					}					
				}
			}

			if (storePathList.size() > 0 && storePathList.size() == fileList.size()) {
				boolean bResult=msFileServiceImpl.batchDeleteFiles(fileList);
				if(bResult)fdfsClient.batchDeleteFile(storePathList);
			}
			strResult="SUCCESS";
		} catch (Exception e) {
			log.error("Delete file exception,received files infomation is:" + allFilesInfo);
			log.error(e.getMessage());
			strResult="ERROR";
		}

		try {
			response.getWriter().write(strResult);
		} catch (Exception e) {

		}
		// msFileServiceImpl
	}
}
